/**
 * Created by wx on 2017/5/14.
 */
var Promise = require('bluebird'),
    path = require('path'),
    _ = require('lodash'),
    sendToWormhole = require('stream-wormhole'),
    pipeline = require("../../utils/pipeline"),
    fs = require('fs');
module.exports = app => {
    class files extends app.Service {
        * fileupload(_path) {
            const stream = yield this.ctx.getFileStream();
            const name = _path + path.basename(stream.filename);//egg-multipart-test
            const writeStream = fs.createWriteStream(name);

            try {
                return new Promise(function(resolve) {
                    stream.on('data', function (chunk) {
                        if (writeStream.write(chunk) === false) {
                            stream.pause();
                        }
                    });
                    writeStream.on('drain', function () {
                        stream.resume();
                    });
                    stream.on("end", function () {
                        writeStream.end("The end.", function () {
                            console.log("文件全部写入完毕。");
                            console.log("共写入%d字节数据。", writeStream.bytesWritten);
                            resolve({
                                size:writeStream.bytesWritten+"字节",
                                name:path.basename(stream.filename),
                                path:name,
                            });
                        });
                    });
                });
            } catch (err) {
                // 必须将上传的文件流消费掉，要不然浏览器响应会卡死
                yield sendToWormhole(stream);
                throw err;
            }
        }
        * getfiles(_path){
            return new Promise(function(resolve) {

                fs.readdir(_path, function(err, files) {
                    console.log(_path,files)
                })


                    resolve({
                    path:_path,
                });
            })
        }
    }
    return files;
};
